package alp.starcode.nudtportal.framework.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Slf4j
@Component
public class UpLoadFileUtil {
    @Value("${data.send.url}")
    public void setUrl(String url) {
        UpLoadFileUtil.url = url;
    }

    @Value("${data.send.applicationUuid}")
    public void setApplicationUuid(String applicationUuid) {
        UpLoadFileUtil.applicationUuid = applicationUuid;
    }

    @Value("${data.send.token}")
    public void setToken(String token) {
        UpLoadFileUtil.token = token;
    }

    private static String url;
    private static String applicationUuid;
    private static String token;

    /**
     * 文件类型数据上传至发送端
     *
     * @param data 数据
     */
    public static boolean sendFile(byte[] data) {
        boolean result = true;
        try {
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            // 初始化SSL上下文
            sslContext.init(null, new TrustManager[]{tm}, null);
            // SSL套接字连接工厂,NoopHostnameVerifier为信任所有服务器
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).setMaxConnTotal(50)
                    .setMaxConnPerRoute(50).setDefaultRequestConfig(RequestConfig.custom()
                            .setConnectionRequestTimeout(60000).setConnectTimeout(60000).setSocketTimeout(60000).build())
                    .build()) {
                //创建post方式请求对象
                HttpPost httpPost = new HttpPost(url);
                ByteArrayBody byteArrayBody = new ByteArrayBody(data, "微门户数据交换数据");
                //计算签名
                byte[] beforeSignByteArray = new byte[data.length + token.getBytes().length];
                System.arraycopy(data, 0, beforeSignByteArray, 0, data.length);
                System.arraycopy(token.getBytes(), 0, beforeSignByteArray, data.length, token.getBytes().length);
                String sign = DigestUtils.md5Hex(beforeSignByteArray);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                // 解决上传中文名文件乱码
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                builder.setCharset(StandardCharsets.UTF_8);
                //请求的参数
                HttpEntity reqEntity = builder
                        .addPart("file", byteArrayBody)
                        .addTextBody("sign", sign)
                        .addTextBody("applicationUuid", applicationUuid)
                        .setCharset(StandardCharsets.UTF_8)
                        .build();
                httpPost.setEntity(reqEntity);
                //执行请求操作，并拿到结果
                try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        JSONObject jsonObject = JSON.parseObject(IOUtils.toString(resEntity.getContent()));
                        log.info("响应:{}", jsonObject.toJSONString());
                        EntityUtils.consume(resEntity);
                        if (jsonObject.getString("code").equals("200")) {
                            return result;
                        }
                        result = false;
                    }
                }
            }
        } catch (Exception exception) {
            log.error("上传数据异常", exception);
            result = false;
        }
        return result;
    }
}
